package com.wl.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        // 得到要下载的文件名
        String fileName = req.getParameter("fileName");
        // 得到绝对路径
        String path = this.getServletContext().getRealPath("/upload");

        if (!Files.exists(Paths.get(path,fileName))){
            resp.setContentType("text/html;charset=utf-8");
            resp.setCharacterEncoding("utf-8");
            PrintWriter out = resp.getWriter();
            out.write("文件不存在");
            out.flush();
        }else{
            // 得到输出流
            resp.setContentType("octet/stream;charset=utf-8");
            resp.setHeader("Content-disposition","attachment;filename=" + fileName);
            ServletOutputStream os = resp.getOutputStream();
            FileInputStream fis = new FileInputStream(path+"/"+fileName);
            byte[] content = new byte[fis.available()];
            fis.read(content);
            os.write(content);
            os.flush();
            os.close();
            fis.close();
        }

    }
}
